<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/user">User</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
    <script>
      const Home = {
        template: `<div>Home</div>`,
      };
      const User = {
        template: `<div>User</div>`,
      };
      const Profile = {
        template: `<div>Profile</div>`,
      };
      const routes = [
        { 
          name: "home", 
          path: "/", 
          component: Home 
        },
        { 
          name: "user", 
          path: "/user", 
          component: User 
        },
        { 
          name: "profile", 
          path: "/profile", 
          component: Profile 
        }
      ];

      var router = new VueRouter({
        routes,
      });
      /**
       * 1.当一个导航触发时，全局前置守卫按创建的顺序依次调用，
       * 它是异步执行的，守卫resolve之前导航处于等待当中
       * to 即将要进入的目标路由对象
       * from 即将要离开的路由对象
       * next 因为beforeEach异步执行的，所以需要通过next来表示执行完毕
       * 所以一定在要函数中调用next来resolve当前的守卫钩子
       */
      router.onError((error)=>{
       console.log(error)
      })
      router.beforeEach((to,from,next)=>{
        console.log(`beforeEach1`,from,to)
        //next()表示调用下一个钩子或让导航进入确认状态
        //next(false);放弃当前导航
        /* if(to.path !== '/profile'){
          next('/profile');
        }else{
          next();
        } */
        //next(new Error('beforeEach报错啦'));
        next();
        next();
      });
      router.beforeEach((to,from,next)=>{
        console.log(`beforeEach2`,from,to)
        next();
      });
      var vm = new Vue({
        el: "#app",
        router,
      });
    </script>
  </body>
</html>
